import axios from 'axios';
import type { VoiceRecord, Device, AuthResponse, DeviceRegisterResponse } from '@/types';
import { config, getApiUrl } from '@/utils/config';

console.log('API配置:', config.api);

const api = axios.create({
  baseURL: config.api.baseUrl,
  timeout: config.api.timeout,
  headers: {
    'Content-Type': 'application/json',
  }
});

// 请求拦截器 - 添加token和调试信息
api.interceptors.request.use(
  (config) => {
    console.log('API Request:', config.method?.toUpperCase(), config.url, config.data);
    
    const token = localStorage.getItem('smartinput-mobile-token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('API Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误和调试信息
api.interceptors.response.use(
  (response) => {
    console.log('API Response:', response.status, response.config.url, response.data);
    return response;
  },
  (error) => {
    console.error('API Response Error:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      url: error.config?.url,
      message: error.message,
      data: error.response?.data
    });
    
    if (error.response?.status === 401) {
      console.log('Token已失效，清除本地存储');
      localStorage.removeItem('smartinput-mobile-token');
      localStorage.removeItem('smartinput-mobile-user');
      // 触发页面刷新以重新登录
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  login: async (username: string, password: string): Promise<AuthResponse> => {
    const response = await api.post('/api/auth/login', { userName: username, password });
    return response.data;
  },
  
  register: async (username: string, password: string): Promise<AuthResponse> => {
    const response = await api.post('/api/auth/register', { userName: username, password });
    return response.data;
  },
  
  validateToken: async (): Promise<boolean> => {
    try {
      const response = await api.get('/api/auth/validate');
      return response.status === 200;
    } catch (error) {
      return false;
    }
  },
};

// 设备相关API
export const deviceAPI = {
  register: async (deviceName: string, deviceId?: string): Promise<DeviceRegisterResponse> => {
    const requestBody = {
      deviceId: deviceId || `mobile_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      deviceName,
      deviceType: 'mobile_app'
    };
    
    console.log('设备注册请求:', requestBody);
    const response = await api.post('/api/devices/register', requestBody);
    return response.data;
  },
  
  updateStatus: async (deviceId: string, online: boolean): Promise<void> => {
    await api.put(`/api/devices/${deviceId}/status`, { online });
  },
  
  heartbeat: async (deviceId: string): Promise<void> => {
    await api.post(`/api/devices/${deviceId}/heartbeat`);
  },

  // 获取用户所有设备
  getUserDevices: async (): Promise<Device[]> => {
    const response = await api.get('/api/devices');
    console.log('getUserDevices API响应:', response);
    
    // 处理不同的响应格式
    if (response.data && response.data.success && Array.isArray(response.data.data)) {
      return response.data.data;
    } else if (Array.isArray(response.data)) {
      return response.data;
    } else {
      console.warn('getUserDevices返回了意外的数据格式:', response.data);
      return [];
    }
  },

  // 获取在线设备
  getOnlineDevices: async (): Promise<Device[]> => {
    const response = await api.get('/api/devices/online');
    console.log('getOnlineDevices API响应:', response);
    
    // 处理不同的响应格式
    if (response.data && response.data.success && Array.isArray(response.data.data)) {
      return response.data.data;
    } else if (Array.isArray(response.data)) {
      return response.data;
    } else {
      console.warn('getOnlineDevices返回了意外的数据格式:', response.data);
      return [];
    }
  },
  
  // 关联匿名设备
  claimDevice: async (deviceId: string): Promise<any> => {
    const response = await api.post(`/api/devices/${deviceId}/claim`);
    console.log('claimDevice API响应:', response);
    return response.data;
  },
};

// 语音识别相关API
export const voiceAPI = {
  // 语音识别API
  recognize: async (audioBlob: Blob, deviceId: string): Promise<any> => {
    const formData = new FormData();
    formData.append('audio', audioBlob);
    formData.append('deviceId', deviceId);
    
    const response = await api.post('/api/voice/recognize/file', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return response.data;
  },

  // 保存语音记录
  saveRecord: async (deviceId: string, text: string, confidence: number): Promise<VoiceRecord> => {
    const response = await api.post('/api/voice/records', {
      deviceId,
      text,
      confidence,
    });
    return response.data;
  },

  // 获取语音记录历史
  getHistory: async (): Promise<VoiceRecord[]> => {
    const response = await api.get('/api/voice/records');
    return response.data;
  },
};

// 文字同步相关API
export const syncAPI = {
  // 推送到指定设备
  pushToDevice: async (sourceDeviceId: string, targetDeviceId: string, content: string): Promise<any> => {
    const response = await api.post('/api/sync/push/device', {
      sourceDeviceId,
      targetDeviceId,
      content,
    });
    return response.data;
  },

  // 推送到所有设备
  pushToAll: async (sourceDeviceId: string, content: string): Promise<any> => {
    const response = await api.post('/api/sync/push/all', {
      sourceDeviceId,
      content,
    });
    return response.data;
  },
}; 